package services

import (
	"context"
	"encoding/json"
	"fmt"
	"math/rand"
	"net/url"
	"strings"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/config"
	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay"
	photonpayModels "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/models"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common/i18n"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
)

// min 返回两个整数中的较小值
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

// GetCardList 获取卡片列表
func GetCardList(ctx context.Context, client *photonpay.PhotonPayClient, params photonpayModels.CardListQueryParams) (*photonpayModels.CardListResponse, error) {
	query := url.Values{}
	if params.PageIndex > 0 {
		query.Set("pageIndex", fmt.Sprintf("%d", params.PageIndex))
	}
	if params.PageSize > 0 {
		query.Set("pageSize", fmt.Sprintf("%d", params.PageSize))
	}
	if params.MatrixAccount != "" {
		query.Set("matrixAccount", params.MatrixAccount)
	}
	if params.CardBin != "" {
		query.Set("cardBin", params.CardBin)
	}
	if params.CreatedAtStart != "" {
		query.Set("createdAtStart", params.CreatedAtStart)
	}
	if params.CreatedAtEnd != "" {
		query.Set("createdAtEnd", params.CreatedAtEnd)
	}
	if params.CardType != "" {
		query.Set("cardType", params.CardType)
	}
	if params.CardFormFactor != "" {
		query.Set("cardFormFactor", params.CardFormFactor)
	}
	if params.CardStatus != "" {
		query.Set("cardStatus", params.CardStatus)
	}

	// 构建请求路径
	path := "/vcc/openApi/v4/pagingVccCard"
	if len(query) > 0 {
		path += "?" + query.Encode()
	}

	if config.GlobalConfig.Server.Mode == "debug" {
		fmt.Printf("[PhotonPay] 获取卡片列表请求路径: %s\n", path)
	}

	// 发送请求
	resp, err := client.Get(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("获取卡片列表失败: %v", err)
	}

	// 解析响应
	var result photonpayModels.CardListResponse
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, fmt.Errorf("解析卡片列表响应失败: %v", err)
	}

	// 检查响应状态
	if result.Code != "0000" {
		return nil, fmt.Errorf("获取卡片列表失败: %s", result.Msg)
	}

	// 标准化响应格式
	standardizeCardListResponse(&result)

	// 获取所有卡片的ID
	cardIDs := make([]string, 0)
	for _, card := range result.Data {
		if card.CardID != "" {
			cardIDs = append(cardIDs, card.CardID)
		}
	}

	// 从数据库中查询卡片昵称和总转账金额
	var cards []models.UserCard
	if err := database.DB.Where("card_id IN ?", cardIDs).Find(&cards).Error; err != nil {
		return nil, fmt.Errorf("查询卡片昵称失败: %v", err)
	}

	// 创建卡片ID到昵称和总转账金额的映射
	type cardExtra struct {
		Nickname            string
		TotalTransferAmount decimal.Decimal
		Exists              bool
	}
	cardExtras := make(map[string]cardExtra)
	for _, card := range cards {
		cardExtras[card.CardID] = cardExtra{
			Nickname:            card.NikeName,
			TotalTransferAmount: card.TotalTransferAmount,
			Exists:              true,
		}
	}

	// 为每个卡片添加昵称和总转账金额
	for i := range result.Data {
		cardID := result.Data[i].CardID
		if extra, exists := cardExtras[cardID]; exists {
			// 卡片已存在于数据库中，使用数据库中的值
			result.Data[i].Nickname = extra.Nickname
			result.Data[i].TotalTransferAmount = extra.TotalTransferAmount.InexactFloat64()
		} else {
			// 卡片首次加载，使用API返回的CardBalance作为TotalTransferAmount
			// 同时创建新的卡片记录到数据库
			cardBalance := result.Data[i].CardBalance
			result.Data[i].TotalTransferAmount = cardBalance

			// 从上下文中获取用户ID
			if userID, exists := ctx.Value("userID").(int64); exists {
				// 创建新的卡片记录
				newCard := models.UserCard{
					UserID:              userID,
					CardID:              cardID,
					Platform:            "photonpay",
					CardStatus:          result.Data[i].CardStatus,
					CardBin:             result.Data[i].CardID[:6], // 取卡ID前6位作为卡BIN
					NikeName:            result.Data[i].Nickname,
					CardType:            result.Data[i].CardType,
					TotalTransferAmount: decimal.NewFromFloat(cardBalance), // 使用CardBalance初始化
					CreatedAt:           time.Now(),
					UpdatedAt:           time.Now(),
				}

				if err := database.DB.Create(&newCard).Error; err != nil {
					// 记录错误但继续处理，不中断流程
					fmt.Printf("[PhotonPay] 创建卡片记录失败: CardID=%s, Error=%v\n", cardID, err)
				} else {
					fmt.Printf("[PhotonPay] 首次加载卡片，创建记录成功: CardID=%s, CardBalance=%.2f\n", cardID, cardBalance)
				}
			} else {
				fmt.Printf("[PhotonPay] 首次加载卡片但未找到用户ID: CardID=%s, CardBalance=%.2f\n", cardID, cardBalance)
			}
		}
	}

	// 记录成功日志
	if config.GlobalConfig.Server.Mode == "debug" {
		fmt.Printf("[PhotonPay] 成功获取卡列表，商户ID: %s, 卡数量: %d\n",
			params.MatrixAccount, len(result.Data))
	}

	return &result, nil
}

// standardizeCardListResponse 标准化卡列表响应格式
// 将响应格式标准化为：code使用"0000"，卡组织使用大写
func standardizeCardListResponse(response *photonpayModels.CardListResponse) {
	// 确保成功码为"0000"
	if response.Code == "200" {
		response.Code = "0000"
	}

	// 标准化每个卡片信息
	for i := range response.Data {
		card := &response.Data[i]

		// 标准化卡组织为大写
		card.CardScheme = strings.ToUpper(card.CardScheme)

		// 标准化卡状态（如果需要）
		card.CardStatus = strings.ToUpper(card.CardStatus)

		// 标准化卡类型（如果需要）
		card.CardType = strings.ToLower(card.CardType)

		// 标准化卡介质（如果需要）
		card.CardFormFactor = strings.ToLower(card.CardFormFactor)
	}
}

// GetCVV 查询卡片的CVV信息
func GetCVV(ctx context.Context, client *photonpay.PhotonPayClient, cardID string) (*photonpayModels.CVVResponse, error) {
	// 构建查询参数
	query := url.Values{}
	query.Set("cardId", cardID)

	// 构建请求路径
	path := "/vcc/openApi/v4/getCvv"
	if len(query) > 0 {
		path += "?" + query.Encode()
	}

	// 发送请求
	resp, err := client.Get(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("get CVV failed: %v", err)
	}

	// 解析响应
	var result photonpayModels.CVVResponse
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, fmt.Errorf("unmarshal response failed: %v", err)
	}

	// 检查响应状态
	if result.Code != "0000" {
		return nil, fmt.Errorf("get CVV failed: %s", result.Msg)
	}

	return &result, nil
}

// GetCardDetail 查询卡片详细信息
func GetCardDetail(ctx context.Context, client *photonpay.PhotonPayClient, cardID string) ([]byte, error) {
	// 构建查询参数
	query := url.Values{}
	query.Set("cardId", cardID)

	// 构建请求路径
	path := "/vcc/openApi/v4/getCardDetail"
	if len(query) > 0 {
		path += "?" + query.Encode()
	}

	// 发送请求
	resp, err := client.Get(ctx, path)
	if err != nil {
		// 构造标准错误响应
		errorResp := map[string]interface{}{
			"code": "500",
			"msg": map[string]string{
				"cn": "获取卡片详情失败",
				"en": "Failed to get card details",
				"vn": "Không thể lấy chi tiết thẻ",
			},
			"data": map[string]string{
				"cn": err.Error(),
				"en": err.Error(),
				"vn": err.Error(),
			},
		}
		respBytes, _ := json.Marshal(errorResp)
		return respBytes, nil
	}

	// 解析为通用的map结构
	var result map[string]interface{}
	if err := json.Unmarshal(resp, &result); err != nil {
		// 构造解析错误响应
		errorResp := map[string]interface{}{
			"code": "500",
			"msg": map[string]string{
				"cn": "获取卡片详情失败",
				"en": "Failed to get card details",
				"vn": "Không thể lấy chi tiết thẻ",
			},
			"data": map[string]string{
				"cn": fmt.Sprintf("parse response failed: %v", err),
				"en": fmt.Sprintf("parse response failed: %v", err),
				"vn": fmt.Sprintf("parse response failed: %v", err),
			},
		}
		respBytes, _ := json.Marshal(errorResp)
		return respBytes, nil
	}

	// 如果是成功响应（code为"0000"）
	if code, ok := result["code"].(string); ok && code == "0000" {
		// 从上下文中获取用户ID
		userID, exists := ctx.Value("userID").(int64)
		if exists && result["data"] != nil {
			if data, ok := result["data"].(map[string]interface{}); ok {
				// 检查卡是否已存在于user_cards表中
				var existingCard models.UserCard
				if err := database.DB.Where("card_id = ?", cardID).First(&existingCard).Error; err != nil {
					if err == gorm.ErrRecordNotFound {
						// 卡不存在，创建新记录
						newCard := models.UserCard{
							UserID:     userID,
							CardID:     cardID,
							Platform:   "photonpay",
							CardStatus: fmt.Sprint(data["cardStatus"]),
							CardBin:    fmt.Sprint(data["cardNo"])[:6], // 取卡号前6位作为卡BIN
							NikeName:   fmt.Sprint(data["nickname"]),
							CardType:   fmt.Sprint(data["cardType"]),
						}
						if err := database.DB.Create(&newCard).Error; err != nil {
							// 记录错误但继续处理
							fmt.Printf("Failed to create card record: %v\n", err)
						}
					}
				}
			}
		}
		return resp, nil
	}

	// 如果是错误响应，保持原始响应格式
	return resp, nil
}

// GetCardCVV 获取卡片CVV
func GetCardCVV(ctx context.Context, client *photonpay.PhotonPayClient, cardID string) ([]byte, error) {
	if cardID == "" {
		return nil, fmt.Errorf("card ID is required")
	}

	// 构建查询参数
	query := url.Values{}
	query.Set("cardId", cardID)

	// 构建请求路径
	path := "/vcc/openApi/v4/getCvv"
	if len(query) > 0 {
		path += "?" + query.Encode()
	}

	if config.GlobalConfig.Server.Mode == "debug" {
		fmt.Printf("[PhotonPay] 获取CVV请求路径: %s\n", path)
	}

	// 发送请求
	resp, err := client.Get(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("get card CVV failed: %v", err)
	}

	// 解析响应
	var result photonpayModels.CVVResponse
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, fmt.Errorf("unmarshal CVV response failed: %v", err)
	}

	// 检查响应状态
	if result.Code != "0000" {
		return nil, fmt.Errorf("get card CVV failed: %s", result.Msg)
	}

	if config.GlobalConfig.Server.Mode == "debug" {
		fmt.Printf("[PhotonPay] 成功获取CVV，卡片ID: %s\n", cardID)
	}

	return resp, nil
}

// PreRecharge 预充值
func PreRecharge(ctx context.Context, client *photonpay.PhotonPayClient, params map[string]string) ([]byte, error) {
	// 构建查询参数
	query := url.Values{}
	for k, v := range params {
		if v != "" {
			query.Set(k, v)
		}
	}

	// 构建请求路径
	path := "/vcc/openApi/v4/preRecharge"
	if len(query) > 0 {
		path += "?" + query.Encode()
	}

	// 发送请求
	resp, err := client.Get(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("pre recharge failed: %v", err)
	}

	// 直接返回响应
	return resp, nil
}

// Recharge 转入下单
func Recharge(ctx context.Context, client *photonpay.PhotonPayClient, bodyBytes []byte) ([]byte, error) {
	path := "/vcc/openApi/v4/recharge"

	resp, err := client.PostWithRawBody(ctx, path, bodyBytes)
	if err != nil {
		return nil, fmt.Errorf("recharge failed: %v", err)
	}

	// 打印原始响应用于调试
	fmt.Printf("Recharge API 原始响应: %s\n", string(resp))

	// 解析响应
	var response struct {
		Code string          `json:"code"`
		Msg  string          `json:"msg"`
		Data json.RawMessage `json:"data"`
	}
	if err := json.Unmarshal(resp, &response); err != nil {
		return nil, fmt.Errorf("unmarshal response failed: %v", err)
	}

	// 检查响应状态 - 支持多种成功码
	if response.Code != "0000" && response.Code != "200" {
		// 尝试从data字段中提取错误信息
		var errorMsg string
		if response.Data != nil {
			var dataArray []map[string]interface{}
			if err := json.Unmarshal(response.Data, &dataArray); err == nil && len(dataArray) > 0 {
				if msg, ok := dataArray[0]["message"].(string); ok {
					errorMsg = msg
				}
			}
		}

		// 如果没有从data中提取到错误信息，使用msg字段
		if errorMsg == "" {
			errorMsg = response.Msg
		}

		// 构造错误响应
		errorResponse := struct {
			Code string `json:"code"`
			Msg  struct {
				CN string `json:"CN"`
				EN string `json:"EN"`
				VN string `json:"VN"`
			} `json:"msg"`
			Data struct {
				CN string `json:"cn"`
				EN string `json:"en"`
				VN string `json:"vn"`
			} `json:"data"`
		}{
			Code: "400",
			Msg: struct {
				CN string `json:"CN"`
				EN string `json:"EN"`
				VN string `json:"VN"`
			}{
				CN: "充值失败",
				EN: "Recharge failed",
				VN: "Nạp tiền thất bại",
			},
			Data: struct {
				CN string `json:"cn"`
				EN string `json:"en"`
				VN string `json:"vn"`
			}{
				CN: errorMsg,
				EN: errorMsg,
				VN: errorMsg,
			},
		}

		errorBytes, _ := json.Marshal(errorResponse)
		return errorBytes, nil
	}

	// 构造标准成功响应
	standardResponse := struct {
		Code string `json:"code"`
		Msg  struct {
			CN string `json:"CN"`
			EN string `json:"EN"`
			VN string `json:"VN"`
		} `json:"msg"`
		Data json.RawMessage `json:"data"`
	}{
		Code: "200",
		Msg: struct {
			CN string `json:"CN"`
			EN string `json:"EN"`
			VN string `json:"VN"`
		}{
			CN: "充值成功",
			EN: "Recharge successful",
			VN: "Nạp tiền thành công",
		},
		Data: response.Data,
	}

	return json.Marshal(standardResponse)
}

// GetVccTradeOrderList 查询卡片交易明细
func GetVccTradeOrderList(ctx context.Context, client *photonpay.PhotonPayClient, params photonpayModels.VccTradeOrderQueryParams) (*photonpayModels.VccTradeOrderListResponse, error) {
	// 从上下文中获取语言参数
	var language string
	var shouldTranslate bool
	if lang := ctx.Value("language"); lang != nil {
		if langStr, ok := lang.(string); ok && langStr != "" {
			language = strings.ToUpper(langStr)
			shouldTranslate = true
		}
	}

	// 添加调试日志
	fmt.Printf("[PhotonPay] 当前语言设置: %s, 是否翻译: %v\n", language, shouldTranslate)

	// 翻译函数
	translate := func(key string) string {
		if !shouldTranslate {
			return key // 如果不翻译，直接返回原值
		}
		translated := i18n.GetMessage(key, i18n.Language(language))
		fmt.Printf("[PhotonPay] 翻译: %s -> %s (语言: %s)\n", key, translated, language)
		return translated
	}

	// 翻译交易类型
	translateTransactionType := func(transactionType string) string {
		if !shouldTranslate {
			return transactionType // 如果不翻译，直接返回原值
		}
		switch strings.ToLower(transactionType) {
		case "auth":
			return translate("transaction_type_auth")
		case "corrective_auth":
			return translate("transaction_type_corrective_auth")
		case "verification":
			return translate("transaction_type_verification")
		case "void":
			return translate("transaction_type_void")
		case "refund":
			return translate("transaction_type_refund")
		case "corrective_refund":
			return translate("transaction_type_corrective_refund")
		case "recharge":
			return translate("transaction_type_recharge")
		case "recharge_return":
			return translate("transaction_type_recharge_return")
		case "discard_recharge_return":
			return translate("transaction_type_discard_recharge_return")
		case "service_fee":
			return translate("transaction_type_service_fee")
		case "refund_reversal":
			return translate("transaction_type_refund_reversal")
		case "fund_in":
			return translate("transaction_type_fund_in")
		case "atm_inquiry":
			return translate("transaction_type_atm_inquiry")
		case "atm_withdrawals":
			return translate("transaction_type_atm_withdrawals")
		case "atm_inquiry_failed_return":
			return translate("transaction_type_atm_inquiry_failed_return")
		case "atm_withdrawals_failed_return":
			return translate("transaction_type_atm_withdrawals_failed_return")
		default:
			return transactionType
		}
	}

	// 翻译交易状态
	translateStatus := func(status string) string {
		if !shouldTranslate {
			return status // 如果不翻译，直接返回原值
		}
		switch strings.ToLower(status) {
		case "pending":
			return translate("status_pending")
		case "authorized":
			return translate("status_authorized")
		case "succeed":
			return translate("status_succeed")
		case "failed":
			return translate("status_failed")
		case "void":
			return translate("status_void")
		case "processing":
			return translate("status_processing")
		default:
			return status
		}
	}

	// 翻译卡类型
	translateCardType := func(cardType string) string {
		if !shouldTranslate {
			return cardType // 如果不翻译，直接返回原值
		}
		switch strings.ToLower(cardType) {
		case "recharge":
			return translate("card_type_recharge")
		case "share":
			return translate("card_type_share")
		default:
			return cardType
		}
	}

	// 翻译卡形态
	translateCardFormFactor := func(cardFormFactor string) string {
		if !shouldTranslate {
			return cardFormFactor // 如果不翻译，直接返回原值
		}
		switch strings.ToLower(cardFormFactor) {
		case "virtual_card":
			return translate("card_form_factor_virtual_card")
		case "physical_card":
			return translate("card_form_factor_physical_card")
		default:
			return cardFormFactor
		}
	}

	if params.PageSize > 1024 {
		allOrders := make([]photonpayModels.VccTradeOrderInfo, 0)
		pageSize := int64(1024)

		// 先获取第一页数据，获取总数
		query := url.Values{}
		query.Set("pageIndex", "1")
		query.Set("pageSize", fmt.Sprintf("%d", pageSize))
		if params.MatrixAccount != "" {
			query.Set("matrixAccount", params.MatrixAccount)
		}
		if params.CardID != "" {
			query.Set("cardId", params.CardID)
		}
		if params.CardType != "" {
			query.Set("cardType", params.CardType)
		}
		if params.RequestID != "" {
			query.Set("requestId", params.RequestID)
		}
		if params.TransactionID != "" {
			query.Set("transactionId", params.TransactionID)
		}
		if params.Status != "" {
			query.Set("status", params.Status)
		}
		if params.TransactionType != "" {
			query.Set("transactionType", params.TransactionType)
		}
		if params.CreatedAtStart != "" {
			query.Set("createdAtStart", params.CreatedAtStart)
		}
		if params.CreatedAtEnd != "" {
			query.Set("createdAtEnd", params.CreatedAtEnd)
		}

		path := "/vcc/openApi/v4/pagingVccTradeOrder"
		if len(query) > 0 {
			path += "?" + query.Encode()
		}

		fmt.Printf("[PhotonPay] 获取第一页数据，请求URL: %s\n", path)

		resp, err := client.Get(ctx, path)
		if err != nil {
			return nil, fmt.Errorf("get vcc trade order list failed: %v", err)
		}

		var firstPageResult photonpayModels.VccTradeOrderListResponse
		if err := json.Unmarshal(resp, &firstPageResult); err != nil {
			return nil, fmt.Errorf("unmarshal response failed: %v", err)
		}

		if firstPageResult.Code != "0000" {
			return nil, fmt.Errorf("get vcc trade order list failed: %s", firstPageResult.Msg)
		}

		// 添加第一页数据
		allOrders = append(allOrders, firstPageResult.Data...)
		fmt.Printf("[PhotonPay] 第一页数据: %d 条\n", len(firstPageResult.Data))

		// 计算总页数
		totalPages := (firstPageResult.Total + pageSize - 1) / pageSize
		fmt.Printf("[PhotonPay] 总数据量: %d, 总页数: %d\n", firstPageResult.Total, totalPages)

		// 如果请求的数据量大于实际数据量，调整pageSize
		if params.PageSize > firstPageResult.Total {
			fmt.Printf("[PhotonPay] 请求数据量(%d)大于实际数据量(%d)，将返回实际数据量\n",
				params.PageSize, firstPageResult.Total)
			params.PageSize = firstPageResult.Total
		}

		// 计算需要获取的页数
		neededPages := (params.PageSize + pageSize - 1) / pageSize
		if neededPages > totalPages {
			neededPages = totalPages
		}
		fmt.Printf("[PhotonPay] 需要获取的页数: %d\n", neededPages)

		// 从第二页开始获取数据
		for pageIndex := int64(2); pageIndex <= neededPages; pageIndex++ {
			// 添加随机请求延时，避免请求过于频繁
			if pageIndex > 2 {
				// 生成1-2秒的随机等待时间
				waitTime := time.Duration(1000+rand.Intn(1000)) * time.Millisecond
				fmt.Printf("[PhotonPay] 等待%.2f秒后继续请求...\n", float64(waitTime)/float64(time.Second))
				time.Sleep(waitTime)
			}

			query.Set("pageIndex", fmt.Sprintf("%d", pageIndex))
			path := "/vcc/openApi/v4/pagingVccTradeOrder"
			if len(query) > 0 {
				path += "?" + query.Encode()
			}

			fmt.Printf("[PhotonPay] 获取第 %d 页数据，请求URL: %s\n", pageIndex, path)

			resp, err := client.Get(ctx, path)
			if err != nil {
				return nil, fmt.Errorf("get vcc trade order list failed: %v", err)
			}

			var result photonpayModels.VccTradeOrderListResponse
			if err := json.Unmarshal(resp, &result); err != nil {
				return nil, fmt.Errorf("unmarshal response failed: %v", err)
			}

			if result.Code != "0000" {
				return nil, fmt.Errorf("get vcc trade order list failed: %s", result.Msg)
			}

			fmt.Printf("[PhotonPay] 第 %d 页数据: %d 条\n", pageIndex, len(result.Data))
			allOrders = append(allOrders, result.Data...)
		}

		// 如果获取的数据量超过请求的pageSize，截取需要的部分
		if int64(len(allOrders)) > params.PageSize {
			allOrders = allOrders[:params.PageSize]
			fmt.Printf("[PhotonPay] 截取数据至请求的pageSize: %d\n", params.PageSize)
		}

		fmt.Printf("[PhotonPay] 查询完成，总共获取数据: %d 条\n", len(allOrders))

		// 获取所有卡片的ID
		cardIDs := make([]string, 0)
		for _, order := range allOrders {
			if order.CardID != "" {
				cardIDs = append(cardIDs, order.CardID)
			}
		}

		// 添加调试信息
		fmt.Printf("[PhotonPay] 需要查询昵称的卡ID数量: %d\n", len(cardIDs))
		if len(cardIDs) > 0 {
			fmt.Printf("[PhotonPay] 前5个卡ID: %v\n", cardIDs[:min(5, len(cardIDs))])
		}

		// 从数据库中查询卡片昵称
		var cards []models.UserCard
		if err := database.DB.Where("card_id IN ?", cardIDs).Find(&cards).Error; err != nil {
			return nil, fmt.Errorf("查询卡片昵称失败: %v", err)
		}

		fmt.Printf("[PhotonPay] 从数据库查询到的卡记录数量: %d\n", len(cards))

		// 创建卡片ID到昵称的映射
		cardNicknames := make(map[string]string)
		for _, card := range cards {
			cardNicknames[card.CardID] = card.NikeName

		}

		// 为每个交易记录添加卡昵称和翻译
		for i := range allOrders {
			if nickname, exists := cardNicknames[allOrders[i].CardID]; exists {
				allOrders[i].CardNickname = nickname
			} else {
				allOrders[i].CardNickname = ""
			}

			// 翻译交易类型
			allOrders[i].TransactionType = translateTransactionType(allOrders[i].TransactionType)

			// 翻译交易状态
			allOrders[i].Status = translateStatus(allOrders[i].Status)

			// 翻译卡类型
			allOrders[i].CardType = translateCardType(allOrders[i].CardType)

			// 翻译卡形态
			allOrders[i].CardFormFactor = translateCardFormFactor(allOrders[i].CardFormFactor)
		}

		// 返回结果
		return &photonpayModels.VccTradeOrderListResponse{
			Code:      "0000",
			Msg:       "success",
			Data:      allOrders,
			PageIndex: params.PageIndex,
			PageSize:  params.PageSize,
			Total:     firstPageResult.Total,
		}, nil
	}

	// 如果页大小小于等于1024，直接发送请求
	query := url.Values{}
	if params.PageIndex > 0 {
		query.Set("pageIndex", fmt.Sprintf("%d", params.PageIndex))
	}
	if params.PageSize > 0 {
		query.Set("pageSize", fmt.Sprintf("%d", params.PageSize))
	}
	if params.MatrixAccount != "" {
		query.Set("matrixAccount", params.MatrixAccount)
	}
	if params.CardID != "" {
		query.Set("cardId", params.CardID)
	}
	if params.CardType != "" {
		query.Set("cardType", params.CardType)
	}
	if params.RequestID != "" {
		query.Set("requestId", params.RequestID)
	}
	if params.TransactionID != "" {
		query.Set("transactionId", params.TransactionID)
	}
	if params.Status != "" {
		query.Set("status", params.Status)
	}
	if params.TransactionType != "" {
		query.Set("transactionType", params.TransactionType)
	}
	if params.CreatedAtStart != "" {
		query.Set("createdAtStart", params.CreatedAtStart)
	}
	if params.CreatedAtEnd != "" {
		query.Set("createdAtEnd", params.CreatedAtEnd)
	}
	// 打印查询参数，用于调试
	fmt.Printf("Query parameters: %v\n", query)

	path := "/vcc/openApi/v4/pagingVccTradeOrder"
	if len(query) > 0 {
		path += "?" + query.Encode()
	}

	resp, err := client.Get(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("get vcc trade order list failed: %v", err)
	}

	var result photonpayModels.VccTradeOrderListResponse
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, fmt.Errorf("unmarshal response failed: %v", err)
	}

	if result.Code != "0000" {
		return nil, fmt.Errorf("get vcc trade order list failed: %s", result.Msg)
	}

	// 获取所有卡片的ID
	cardIDs := make([]string, 0)
	for _, order := range result.Data {
		if order.CardID != "" {
			cardIDs = append(cardIDs, order.CardID)
		}
	}

	// 添加调试信息
	fmt.Printf("[PhotonPay] 需要查询昵称的卡ID数量: %d\n", len(cardIDs))
	if len(cardIDs) > 0 {
		fmt.Printf("[PhotonPay] 前5个卡ID: %v\n", cardIDs[:min(5, len(cardIDs))])
	}

	// 从数据库中查询卡片昵称
	var cards []models.UserCard
	if err := database.DB.Where("card_id IN ?", cardIDs).Find(&cards).Error; err != nil {
		return nil, fmt.Errorf("查询卡片昵称失败: %v", err)
	}

	fmt.Printf("[PhotonPay] 从数据库查询到的卡记录数量: %d\n", len(cards))

	// 创建卡片ID到昵称的映射
	cardNicknames := make(map[string]string)
	for _, card := range cards {
		cardNicknames[card.CardID] = card.NikeName
		fmt.Printf("[PhotonPay] 卡ID: %s, 昵称: %s\n", card.CardID, card.NikeName)
	}

	// 为每个交易记录添加卡昵称和翻译
	for i := range result.Data {
		if nickname, exists := cardNicknames[result.Data[i].CardID]; exists {
			result.Data[i].CardNickname = nickname
		} else {
			result.Data[i].CardNickname = ""
		}

		// 翻译交易类型
		result.Data[i].TransactionType = translateTransactionType(result.Data[i].TransactionType)

		// 翻译交易状态
		result.Data[i].Status = translateStatus(result.Data[i].Status)

		// 翻译卡类型
		result.Data[i].CardType = translateCardType(result.Data[i].CardType)

		// 翻译卡形态
		result.Data[i].CardFormFactor = translateCardFormFactor(result.Data[i].CardFormFactor)
	}

	return &result, nil
}
